package 冒泡排序

import "fmt"

type Comparable interface {
	CompareTo(other interface{}) int
}

func sort(a []Comparable) {
	for i := len(a) - 1; i > 0; i-- {
		for j := 0; j < i; j++ {
			if greater(a[j], a[j+1]) {
				exch(a, j, j+1)
			}
		}
	}
}

func greater(v, w Comparable) bool {
	return v.CompareTo(w) > 0
}

func exch(a []Comparable, i, j int) {
	temp := a[i]
	a[i] = a[j]
	a[j] = temp
}

// 你需要为你要排序的每种类型实现Comparable接口
type Int int

func (i Int) CompareTo(other interface{}) int {
	switch other := other.(type) {
	case Int:
		if i > other {
			return 1
		} else if i < other {
			return -1
		}
		return 0
	default:
		panic(fmt.Sprintf("unsupported type: %T", other))
	}
}

func main() {
	data := []Comparable{Int(3), Int(1), Int(4), Int(1), Int(5), Int(9)}
	sort(data)
	for _, v := range data {
		fmt.Println(v)
	}
}
